import Validate from '/utils/validate';
let validateForm = new Validate();
const app = getApp();

Page({
  data: {
    iconSize: 0,
    showWarnTip: false,
    dateTip:'请选择预约取件时间',
    cityTip: '请选择您所在的区域',
    phone: '',
    arrIndex: 0,
    showDate: false,
    vcode: {
      obj: '发送验证码',
      disabled: false,
      value: '',
    },
    panels: [
      {
        title: '准备材料',
        content: ['请将以下年审代办所需材料备齐','1. 车主身份证复印件正反面','2. 有效期内交强险保单副本原件','3. 行驶证原件 + 复印件','4. 车辆登记证书复印件'],     
      }, {
        title: '客服确认',
        content: ['客服确认给您，确认您的订单信息，核对您填写的资料。'],      
      }, {
        title: '寄送材料',
        content: ['成功下单后一个工作日内，客服会按照您预约的取件时间，安排顺丰快递上门取件。'],      
      }, {
        title: '年审办理',
        content: ['资料审核，审核无误后我们将立即为您办理年检手续。'],
      }, {
        title: '回寄材料',
        content: ['正常情况下3-5个工作日即可将资料、车辆合格证及绿标寄回，敬请查收。'],
      },
    ],
  },
  onLoad(query) {
    // 页面加载
    // 初始化表单验证插件

    //清除缓存
    my.clearStorageSync();
    this.validateForm = new Validate({
      phoneNum:{
        required:true,
        tel:true,
      },
      validateCode:{
        required:true,
        digits:true,
      },
      username:{
        required:true,
      },
      city:{
        required:true,
      },
      address:{
        required:true,
      },
      bookDate:{
        required:true,
      }
    },{
      phoneNum:{
        required:`请正确填写您的手机号码`,    
      },
      validateCode:{
        required:`验证码错误`,
      },
      username:{
        required:`请输入您的中文姓名`,
      },
      address:{
        required:`请输入详细地址`,      
      },
      city:{
        required:`请选择所在区域`,
      },
      bookDate:{
        required:`请选择预约取件时间`,
      }
    });
    // var result =  validate.email(`li@163.com`);
    // //console.log(result);
  },
  bindTimePickerChange(e) {
    //console.log('picker发送选择改变，携带值为', e.detail.value);
    this.setData({
      arrIndex: e.detail.value,
      showDate: true,
      dateTip: '',
    });
  },
  onReady(e) {
    // setTimeout(() => {
    //   my.hideLoading();
    // }, 2000);
  },
  cachePhone(e) {
    this.setData({
        phone: e.detail.value,      
    });
  },
  clearPhoneTip(e){
    this.cachePhone(e);
    this.setData({
      'showWarnTip': false,
      iconSize: 0,
    });
  },
  getValidateCode(e){  //发送手机验证码
    //console.log(e)
    var phoneNum = this.data.phone;
    if(phoneNum.length!=11 || phoneNum.trim()=='' || !(/^1[3|4|5|7|8][0-9]\d{4,8}$/.test(phoneNum))){
      var temp = this;
      showTip(temp,'请正确填写您的手机号码');
      this.setData({
        iconSize: 23,
        phone: e.detail.value,
      });
      return;
    }

    //调用验证码接口获取验证码
    //console.log(phoneNum)
    my.httpRequest({
      url: app.validateCode_url,
      data: {
        tel: phoneNum,
      },
      method: 'GET',
      success: (res) => {
        //console.log(res)
        this.setData({
          'vcode.value': res.data.data.code,
        });
      },
      fail: function(res) {
        //console.log({content: '获取验证码失败'});
      },
      complete: function(res) {
        // my.hideLoading();
      }
    });

    var that = this;
    if (that.data.vcode!=null) {
      my.showToast({
        type: 'success',
        duration: 2000,
        content: '验证码已发送',
      })
      //开始倒计时60秒
      countDown(that, 60);
    }  
  },
  chooseCity(e){  //区域选择器（方案一）
    // my.chooseCity({
    //   showLocatedCity: true,
    //   showHotCities: true,
    //   success: (res) => {
    //     this.setData({
    //       city:res.city+`市`,
    //       cityTip:``,
    //     });
    //   },
    // });

    my.chooseCity({
      cities: [
        {
          city: '广州市',
          adCode: '510000',
          spell: 'guangzhou'
        },
        {
          city: '深圳市',
          adCode: '518000',
          spell: 'shenzhen'
        },
        {
          city: '梅州市',
          adCode: '514000',
          spell: 'meizhou'
        },
        {
          city: '云浮市',
          adCode: '527100',
          spell: 'yunfu'
        },
        {
          city: '清远市',
          adCode: '511500',
          spell: 'qingyuan'
        },
        {
          city: '珠海市',
          adCode: '519000',
          spell: 'zhuhai'
        },
        {
          city: '河源市',
          adCode: '517000',
          spell: 'heyuan'
        },
        {
          city: '揭阳市',
          adCode: '522000',
          spell: 'jieyang'
        },
        {
          city: '韶关市',
          adCode: '511100',
          spell: 'shaoguan'
        },
        {
          city: '阳江市',
          adCode: '529500',
          spell: 'yangjiang'
        },
        {
          city: '肇庆市',
          adCode: '526000',
          spell: 'zhaoqing'
        },
        {
          city: '中山市',
          adCode: '528400',
          spell: 'zhongshan'
        },
        {
          city: '东莞市',
          adCode: '523000',
          spell: 'dongguan'
        },
        {
          city: '湛江市',
          adCode: '524000',
          spell: 'zhanjiang'
        },
        {
          city: '江门市',
          adCode: '529000',
          spell: 'jiangmen'
        },
        {
          city: '汕头市',
          adCode: '515000',
          spell: 'shantou'
        },
        {
          city: '潮州市',
          adCode: '515600',
          spell: 'chaozhou'
        },
        {
          city: '佛山市',
          adCode: '528000',
          spell: 'jiangmen'
        },
        {
          city: '惠州市',
          adCode: '512200',
          spell: 'huizhou'
        },
        {
          city: '茂名市',
          adCode: '525000',
          spell: 'huizhou'
        },
        {
          city: '汕尾市',
          adCode: '516400',
          spell: 'shanwei'
        }
      ],
      hotCities: [
        {
          city: '广州市',
          adCode: '510000'
        },
        {
          city: '深圳市',
          adCode: '518000'
        },
        {
          city: '佛山市',
          adCode: '528000'
        }
      ],
      showHotCities:true,
      success: (res) => {
        this.setData({
          city:'广东省'+' '+res.city,
          cityTip:``,
        });
      },
    });
  },
  getTimeSelector(){   //日期选择器       
    var newDate = new Date();
    my.datePicker({ 
      currentDate: GetDateStr(0.2), 
      startDate: GetDateStr(0.2), 
      endDate: GetDateStr(5),
      format: 'yyyy-MM-dd HH:mm',
      success: (res) => {

        var hour = res.date.split(' ')[1].split(':')[0];
        var day = res.date.split(' ')[0].split('-')[2];
        var temp = this;
        if(hour<=newDate.getHours()+4 && parseInt(day)===newDate.getDate()){
          //预约时间不符合要求，显示提示
          showTip(temp,'预约时间须大于当前时间四个小时');
          return;
        }else if(hour<9 || hour>17){
          showTip(temp,'预约时间须在工作时间段内');
          return;
        }else {
          this.setData({
            bookDate: res.date,
            bdate: res.date,
            dateTip:``
          });
        }
      }, 
    });
    
  }, 
  onUnload() {
    // 关闭程序
  },
  goToFlowPage(){
    //重定向至业务办理流程页面
    my.navigateBack({
      delta: 1
    })
  },
  onSubmit(e) {
    
    //表单字段校验
    var dataSet = JSON.stringify(e.detail.value);
    //console.log(dataSet);
    if(!this.validateForm.checkForm(e)){
      const error = this.validateForm.errorList[0];
      var temp = this;
      showTip(temp,error.msg);
      return;
    }

    //整理数据，拼接url
    var tel = this.data.phone;
    var sms_code = e.detail.value.validateCode;
    var username = e.detail.value.username;
    var area = this.data.city;
    var area_info = e.detail.value.address;
    var appointe_time = this.data.bdate;
    //console.log(this.data.vcode.value)
    //校验验证码
    if(sms_code!=this.data.vcode.value){
      var temp = this;
      showTip(temp,'验证码错误');
      return;
    }
    my.setStorageSync({
      key: 'bookInfo',
      data: {
        tel: tel,
        sms_code: sms_code,
        area: area,
        username: username,
        area_info: area_info,
        appointe_time: appointe_time,
      }
    });
    //提交表单信息，导航至车辆信息页面
    my.navigateTo({ 
      url: '../check-car-info/check-car-info?tel='+tel+'&sms_code='+sms_code+'&username='+username+'&area='+area+'&area_info='+area_info+'&appointe_time='+appointe_time
    });
  },

  
});

//显示提示
function showTip(temp,msg) {
  temp.setData({
    'showWarnTip': true,
    'tipBanner': msg,
  })
  if(temp.data.showWarnTip){
    tipCountDown(temp,3);
  }
}

//倒计时60s 间隔任务
function countDown(that,count) {
  if (count == 0) {
    that.setData({
      'vcode.disabled':false,
      'vcode.obj':'发送验证码',
    })
    return;
  }

  that.setData({
    'vcode.disabled':true,
    'vcode.obj': (count)+'秒后重发',
  })
  
  setTimeout(function(){
    count--;
    countDown(that, count);
  }, 1000);
}

//获取N天后的日期字符串
function GetDateStr(AddDayCount) {   
  var dd = new Date(); 
  if(AddDayCount<1 && dd.getHours()>=17){
    AddDayCount=1;
  }
  dd.setDate(dd.getDate()+AddDayCount);//获取AddDayCount天后的日期  
  var y = dd.getFullYear();   
  var m = (dd.getMonth()+1)<10?"0"+(dd.getMonth()+1):(dd.getMonth()+1);//获取当前月份的日期，不足10补0  
  var d = dd.getDate()<10?"0"+dd.getDate():dd.getDate();//获取当前几号，不足10补0  
  var h = "9:00";
  return y+"-"+m+"-"+d+" "+h; 
     
} 


//倒计时3s 错误提示消失
function tipCountDown(that,count){
  if (count == 0) {
    that.setData({
      'showWarnTip':false,
    })
    return;
  }

  setTimeout(function(){
    count--;
    tipCountDown(that, count);
  }, 1000);
}


Date.prototype.format = function(format) {
    var returnStr = '';
    var replace = Date.replaceChars;
    for (var i = 0; i < format.length; i++) {       
        var curChar = format.charAt(i);         
        if (i - 1 >= 0 && format.charAt(i - 1) == "\\") {
            returnStr += curChar;
        }
        else if (replace[curChar]) {
            returnStr += replace[curChar].call(this);
        } else if (curChar != "\\"){
            returnStr += curChar;
        }
    }
    return returnStr;
};


Date.replaceChars = {
    shortMonthsNum: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
    shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
    shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
    longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],

    // Day
    d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
    D: function() { return Date.replaceChars.shortDays[this.getDay()]; },
    j: function() { return this.getDate(); },
    l: function() { return Date.replaceChars.longDays[this.getDay()]; },
    N: function() { return this.getDay() + 1; },
    S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); },
    w: function() { return this.getDay(); },
    z: function() { var d = new Date(this.getFullYear(),0,1); return Math.ceil((this - d) / 86400000); }, // Fixed now
    // Week
    W: function() { var d = new Date(this.getFullYear(), 0, 1); return Math.ceil((((this - d) / 86400000) + d.getDay() + 1) / 7); }, // Fixed now
    // Month
    F: function() { return Date.replaceChars.longMonths[this.getMonth()]; },
    m: function() { return (this.getMonth() < 9 ? '0' : '') + (this.getMonth() + 1); },
    M: function() { return Date.replaceChars.shortMonthsNum[this.getMonth()]; },
    n: function() { return this.getMonth() + 1; },
    t: function() { var d = new Date(); return new Date(d.getFullYear(), d.getMonth(), 0).getDate() }, // Fixed now, gets #days of date
    // Year
    L: function() { var year = this.getFullYear(); return (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)); },   // Fixed now
    o: function() { var d  = new Date(this.valueOf());  d.setDate(d.getDate() - ((this.getDay() + 6) % 7) + 3); return d.getFullYear();}, //Fixed now
    Y: function() { return this.getFullYear(); },
    y: function() { return ('' + this.getFullYear()).substr(2); },
    // Time
    a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
    A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
    B: function() { return Math.floor((((this.getUTCHours() + 1) % 24) + this.getUTCMinutes() / 60 + this.getUTCSeconds() / 3600) * 1000 / 24); }, // Fixed now
    g: function() { return this.getHours() % 12 || 12; },
    G: function() { return this.getHours(); },
    h: function() { return ((this.getHours() % 12 || 12) < 10 ? '0' : '') + (this.getHours() % 12 || 12); },
    H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
    i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
    s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
    u: function() { var m = this.getMilliseconds(); return (m < 10 ? '00' : (m < 100 ?
'0' : '')) + m; },
    // Timezone
    e: function() { return "Not Yet Supported"; },
    I: function() {
        var DST = null;
            for (var i = 0; i < 12; ++i) {
                    var d = new Date(this.getFullYear(), i, 1);
                    var offset = d.getTimezoneOffset();

                    if (DST === null) DST = offset;
                    else if (offset < DST) { DST = offset; break; }                     else if (offset > DST) break;
            }
            return (this.getTimezoneOffset() == DST) | 0;
        },
    O: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + '00'; },
    P: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + ':00'; }, // Fixed now
    T: function() { var m = this.getMonth(); this.setMonth(0); var result = this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/, '$1'); this.setMonth(m); return result;},
    Z: function() { return -this.getTimezoneOffset() * 60; },
    // Full Date/Time
    c: function() { return this.format("Y-m-d\\TH:i:sP"); }, // Fixed now
    r: function() { return this.toString(); },
    U: function() { return this.getTime() / 1000; }
};